package com.usian.admin.gateway.filter;


import com.usian.admin.gateway.utils.AppJwUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();  // 获取用户的请求路径以及携带的参数
        ServerHttpResponse response = exchange.getResponse(); // 帮我们做相应到浏览器上 返还 401认证失败
        if(request.getURI().getPath().contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }
        String jwtToken =  request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(jwtToken)){
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // jwtToken 是有值的  但是不确定是否合法
        try {
            //直接解析Token 确定合法
            Claims claims = AppJwUtil.getClaimsBody(jwtToken);
            //直接携带token放行
            request.mutate().header("token",jwtToken);
            return chain.filter(exchange);
        }catch (Exception e){
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
